package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server4 {
    private ServerSocket serverSocket;

    public Server4(){
        try {
            System.out.println("正在启动服务器....");
            serverSocket = new ServerSocket(8092);
            System.out.println("服务器启动完毕!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){

        try {
            while(true){
                System.out.println("等待客户端连接..");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端已经连接!");
                Runnable runnable = new clientHendler(socket);
                Thread t = new Thread(runnable);
                t.start();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private class clientHendler implements Runnable{
        private Socket socket;
        private String host;

        public clientHendler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        public void run(){

            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(
                                socket.getInputStream()
                        )
                );
                String message;
                while ((message = br.readLine()) != null){
                    System.out.println(host+"说:"+message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


    public static void main(String[] args) {
        Server4 server4 = new Server4();
        server4.start();
    }
}
